package com.example.usercenter.sys.web;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.example.usercenter.common.base.Page;
import com.example.usercenter.common.base.ResponseData;
import com.example.usercenter.sys.entity.LoggerVM;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Controller for view and managing Log Level at runtime.
 */
@RestController
@RequestMapping("/logger")
public class LoggerController {

    @PostMapping("/list")
    @ResponseBody
    @PreAuthorize("hasAuthority('LOGGER')")
    public ResponseData getList() {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        List<LoggerVM> list = context.getLoggerList()
            .stream()
            .map(LoggerVM::new)
            .collect(Collectors.toList());
        Page page = new Page();
        page.setRows(list);
        page.setTotal(list.size());
        return ResponseData.ok("获取日志级别列表成功", page);
    }

    @PutMapping("")
    @ResponseBody
    @PreAuthorize("hasAuthority('LOGGER')")
    public ResponseData changeLevel(@RequestBody LoggerVM jsonLogger) {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel()));
        return ResponseData.ok("操作成功");
    }
}
